package com.example.xf_evaluate

import android.content.Context
import android.util.Log
import com.iflytek.aiui.vad.sdk.EVad
import com.iflytek.aiui.vad.sdk.Vad
import com.iflytek.aiui.vad.sdk.VadConstant
import java.io.IOException
import java.io.InputStream

object VadManager {
    private const val TAG = "ebook VadManager"
    private var mVad: Vad? = null
    private val APP_ID = "7e116a32"

    private var mListener: Vad.VadListener? = null

    fun setListener(value: Vad.VadListener?) {
        mListener = value
    }


    private var mVadListener = object : Vad.VadListener {
        override fun onAuthSuccess() {
            Log.d(TAG, "Vad授权成功")
        }

        override fun onResult(p0: Int, p1: ByteArray?, p2: Int, p3: Int) {
            mListener?.onResult(p0, p1, p2, p3)
        }

        override fun onError(p0: Int, p1: String?) {
//      NLogger.d(TAG, "Vad错误，$p0 , $p1")

            mListener?.onError(p0, p1)
        }

    }

    /**
     * 初始化
     */
    fun init(context: Context) {
        Log.d(TAG, "init: 初始化000")
        try {
            if (mVad == null) {
                //测试appid：e4cddea8 ， 正式使用请注册aiui账号并开通正式授权
                val vadRes = readAsset(context, "evad.jet")
//        val deviceId = "1179145937"
                val macAddress = MacAddressHelper.getPsuedoUniqueID()
                Log.d(TAG, "init: 初始化111 ${vadRes?.size} , 获取到Mac地址 $macAddress")
                val params = "sn=$macAddress,appid=${APP_ID}"
                Log.d(TAG, "init: params: $params")
                mVad = EVad.createInstance(params, vadRes, vadRes?.size ?: 0, mVadListener)
                Log.d(TAG, "init: 初始化222")
                // 参数设置示例
                mVad?.setParameter(VadConstant.KEY_BOS_THRESHOLD, "0.7")
                // 超时时长设置
                mVad?.setParameter(VadConstant.KEY_BOS_TIMEOUT, "3000")
                mVad?.setParameter(VadConstant.KEY_EOS_TIMEOUT, "2000")
                mVad?.requestAuth()
            }
        } catch (e: Exception) {
            Log.d(TAG, "init: 初始化出错！${e.message}")
        }
        Log.d(TAG, "init: 初始化333")
    }

    private fun readAsset(context: Context, filePath: String): ByteArray? {
        try {
            val ins: InputStream = context.assets.open(filePath)
            val buffer = ByteArray(ins.available())
            ins.read(buffer)
            ins.close()
            return buffer
        } catch (e: IOException) {
            e.printStackTrace()
        }
        return null
    }

    fun detect(data: ByteArray, len: Int) {
        Log.d(TAG, "detect: 收到数据流 mVad：$mVad , data : $data ,len: $len")
        mVad?.detect(data, len)

    }

    fun reset() {
        mVad?.reset()
    }
}